package hanlen.mq.starter.support.thread;

import hanlen.mq.starter.configuration.properties.HanlenMqProperties;
import hanlen.mq.starter.constants.QueueConstants;
import hanlen.mq.starter.core.ThreadPoolExecutorService;
import hanlen.mq.starter.support.QueueUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * mq-spring-boot-starter
 *
 * @author MrYe
 * @date 2021-10-25 18:14
 */
@Slf4j
public class AsyncThreadPoolChecker {

    @Autowired
    private ThreadPoolExecutorService executorService;

    @Autowired
    private HanlenMqProperties mqProperties;

    public void monitor() {
        Map<String, Integer> threadConfig = MapUtils.isEmpty(mqProperties.getThreads()) ? new HashMap<>(0) : mqProperties.getThreads();
        final int blockQueueSize = QueueUtil.defaultIfNull(threadConfig.get(QueueConstants.BLOCK_QUEUE_SIZE), 1024);

        final ThreadPoolExecutor threadPoolExecutor = executorService.threadPoolExecutor();
        final long queueSize = threadPoolExecutor.getQueue().size();
        final String msg = String.format("mq-线程池健康检查 名称: asyncExecutor 池大小: %d (当前活动线程数: %d, 核心线程的数量: %d, 允许的最大线程数: %d, 曾经创建过的最大线程数: %d), 需要执行的总任务数: %d (完成任务数: %d)(队列总大小: %d 排队线程数: %d)"
                + " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s)",
            threadPoolExecutor.getPoolSize(), threadPoolExecutor.getActiveCount(), threadPoolExecutor.getCorePoolSize(), threadPoolExecutor.getMaximumPoolSize(),
            threadPoolExecutor.getLargestPoolSize(), threadPoolExecutor.getTaskCount(), threadPoolExecutor.getCompletedTaskCount(), blockQueueSize, queueSize,
            threadPoolExecutor.isShutdown(), threadPoolExecutor.isTerminated(), threadPoolExecutor.isTerminating());
        final long warnQueueSize = blockQueueSize / 4;
        if (queueSize > warnQueueSize) {
            log.warn("警告！线程池: mq-排队线程数超过总队列大小四分之一!! {}", msg);
        } else {
            log.info(msg);
        }
    }

}
